package com.hsmpay.mobile.action.account.qian48;

import com.hsmpay.common.pojo.qian4.Qian4SendLog;
import com.hsmpay.common.pojo.user.User;
import com.hsmpay.common.util.DateConvertUtil;
import com.hsmpay.common.util.URLDecoderTools;
import com.hsmpay.common.util.system.Constant;
import com.hsmpay.mobile.pojo.trans.TransOrder;
import com.hsmpay.mobile.pojo.trans.TransPriorSettle;
import com.hsmpay.mobile.service.trans.TransPriorSettleService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import sun.misc.BASE64Decoder;
import com.hsmpay.utils.TimeUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 千48交易 action
 *
 * @author 颜铃璋
 * @date 2013-8-27
 */
@Controller("q4PurchaseAction")
@Scope("prototype")
public class Q4PurchaseAction extends Q4BaseAction {
    private static final long serialVersionUID = -6685556721396542845L;
    private static final Logger log = Logger.getLogger(Q4PurchaseAction.class);

    private TransOrder transOrder;
    private TransPriorSettle transPriorSettle;
    private Integer clientType;//客户端类型 客户端类型：1网站 2安卓 3iphone 4ipad IOS转码问题 IOS必填

    @Resource(name = "transPriorSettleService")
    private TransPriorSettleService<TransPriorSettle, Long> transPriorSettleService;

    /**
     * 上传签名
     *
     * @return
     */
    public String picUpload() throws Exception {
        log.debug("--- picUpload() start ---");
        JSONObject js = JSONObject.fromObject(getRequest().getAttribute(FC_DATA));
        clientType = Integer.parseInt(js.getString("clientType"));
        terminalTypeId = Long.parseLong(js.getString("terminalTypeId"));
        roleId = Long.parseLong(js.getString("roleId"));
        if (js.containsKey("userId"))
            userId = Long.parseLong(js.getString("userId"));
        if (js.containsKey("receivablesId"))
            receivablesId = Long.parseLong(js.getString("receivablesId"));
        if (js.containsKey("picBuffer")) {
            picBuffer = js.getString("picBuffer");
        }

        log.debug("userId = " + userId);//终端代码
        log.debug("clientType = " + clientType);//
        log.debug("terminalTypeId = " + terminalTypeId);//
        log.debug("receivablesId = " + receivablesId);//收款ID

        if (null == userId) {
            log.warn("上传签名时, 传入参数userId为空");
            sendAppErrorMsg("6001", "userId");
            return null;
        }
        if (StringUtils.isBlank(picBuffer)) {
            log.warn("上传签名时, 传入参数picBuffer为空");
            sendAppErrorMsg("6001", "picBuffer");
            return null;
        }
        User user = null;
        try {
            functionKey = "RECEIVABLES";
            if (!checkPIV(functionKey)) {
                log.warn("我要收款时, 银行接口暂停使用！");
                return null;
            }

            user = userService.getUserById(userId);
            if (null != user) {
                if (roleId.equals(1l) || roleId.equals(2l) || roleId.equals(3l) || roleId.equals(4l) || roleId.equals(5l)) {//简易型  加密
                    if (null != receivablesId) {
                        transPriorSettle = new TransPriorSettle();
                        transPriorSettle.setId(receivablesId);
                        transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);
                        transOrder = new TransOrder();
                        transOrder.setOrderNum(transPriorSettle.getOrderNum());
                        transOrder = transOrderService.searchEntity(transOrder);
                        signaturePath = savaPic(picBuffer, userId, transOrder);
                    } else {
                        signaturePath = savaPic(picBuffer, userId, null);
                    }
                }

                sendTime = TimeUtils.getDateTimeToString();
                sendSeqId = TimeUtils.getTimeToString();

                Map<String, Object> result = new HashMap<String, Object>();
                log.debug("上传签名成功");
                result.put("reqCode", "0000");
                result.put("reqMsg", "上传签名成功!");
                result.put("signaturePath", signaturePath);
                sendAppMsg(result);
            } else {
                log.warn("余额查询时, 用户Id=" + userId + " 对应的用户不存在!");
                sendAppErrorMsg("6012", userId + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            user = null;
            transPriorSettle = null;
            js = null;
            picBuffer = null;
            log.debug("--- picUpload() end ---");
        }
        return null;
    }

    /**
     * 测试返回的 签名图片
     */
    private String savaPic(String picBuffer, Long userId, TransOrder order) throws Exception {
        //log.debug("图片加密文："+picBuffer);
        if (StringUtils.isBlank(picBuffer)) {
            log.debug("图片加密文是空的");
            return null;
        }
        Date date = new Date();
        try {
            String dateTimeStr = DateConvertUtil.dateString(date, "yyyyMMddhhmmssSSS");
            String dateStr = DateConvertUtil.dateString(date);
            String baseUrl = Constant.getAttribute("SERVER_SIGNATURE_URL");
            //拼接 目录绝对路径
            StringBuilder sb = new StringBuilder();
            String dirRelPath = getRealPath(sb.append(baseUrl).append(dateStr).toString());
//            dirRelPath = dirRelPath + "/" + baseUrl + dateStr;
            //拼接 文件绝对路径
            sb = new StringBuilder();
            String imgRelPath = sb.append(dirRelPath).append(File.separator).append(userId).append("_").append(dateTimeStr).append(".png").toString();
            //拼接 文件相对路径
            sb = new StringBuilder();
            String imgPath = sb.append(baseUrl).append(dateStr).append("/").append(userId).append("_").append(dateTimeStr).append(".png").toString();
//            String imgPath = sb.append(baseUrl).append(dateStr).append("/").append(userId).append("_").append(dateTimeStr).append(".png").toString();
            //判断目录存不存在，不存在则创建
            File dirFile = new File(dirRelPath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            byte[] picByte = new BASE64Decoder().decodeBuffer(picBuffer);
            File file = new File(imgRelPath);
            FileOutputStream out = new FileOutputStream(file);
            out.write(picByte);
            out.flush();
            out.close();

            if (null != order) {
                order.setSignaturePath(imgPath);
                transOrderService.updateSignaturePathByNum(order);
            }

            return imgPath;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * http://localhost:8080/proOneMobile/qian48/purchase_batchRevocationOrder.action
     * 批量
     *
     * @return
     * @throws Exception
     */
    public String batchRevocationOrder() throws Exception {
        try {
            TransOrder transOrder = new TransOrder();
            transOrder.setOtherParam("(O.status = 7 OR O.status = 3) ");
            transOrder.setStartDate(DateConvertUtil.stringDate("2014-08-12 23:00:00", "yyyy-MM-dd HH:mm:ss"));
            transOrder.setEndDate(DateConvertUtil.stringDate("2014-08-13 23:00:00", "yyyy-MM-dd HH:mm:ss"));
            transOrder.setOrderTypeId(1L);
            TransPriorSettle transP = new TransPriorSettle();
            transP.setCollectionType(1);
            transOrder.setTransPriorSettle(transP);
            log.error("-------------------------");
            List<TransOrder> transOrderList = transOrderService.searchEntityList(transOrder);
            Map<String, Object> resultMap = null;
            log.error("-------------------------" + transOrderList.size());

            for (TransOrder o : transOrderList) {
                TransPriorSettle transPriorSettle = new TransPriorSettle();
                transPriorSettle.setOrderNum(o.getOrderNum());
                transPriorSettle = transPriorSettleService.searchEntity(transPriorSettle);

                Qian4SendLog send = new Qian4SendLog();
                send.setId(transPriorSettle.getSendId());
                Qian4SendLog srcSend = qian4SendLogService.searchEntity(send);

                Date date = new Date();
                send = new Qian4SendLog();
                send.setCallType(0);
                send.setUserId(o.getUserId());
                send.setApplication("Void.Req");
                send.setOrderTypeId(REVOCATION);
                send.setSendTime(date);
                send.setSendSeqId(TimeUtils.getTimeToString());
                send.setMerchantId(srcSend.getMerchantId());//商户代码 ##
                send.setTerminalId(srcSend.getTerminalId());
                send.setPlatformId(platformId);//平台ID  ##
                send.setTransType("200000");//200000：撤销


                send.setMerchantOrderTime(date);
                send.setTransTime(srcSend.getSendTime());
                send.setMerchantOrderId(DateConvertUtil.dateString(date, "yyyyMMddHHmmssSSS"));
                send.setTransAmt(srcSend.getTransAmt());
                send.setOrgMerchantOrderId(srcSend.getMerchantOrderId());
                send.setCollectionType(srcSend.getCollectionType());
                send.setIp(URLDecoderTools.getRemoteHost(getRequest()));//IP
                long sendId = qian4SendLogService.insertEntity(send);
                send.setId(sendId);
                transOrderService.updateStatusClearing(transPriorSettle.getOrderNum(), 7, null);//发起撤销

                resultMap = accountManageQ4Service.revocationOrder(send);
                log.error("撤销结果 ： " + resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    public TransPriorSettle getTransPriorSettle() {
        return transPriorSettle;
    }

    public TransOrder getTransOrder() {
        return transOrder;
    }

    public void setClientType(Integer clientType) {
        this.clientType = clientType;
    }
}
